import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/route_manager.dart';
import 'package:overload_guard/app_theme.dart';
import 'package:overload_guard/main.dart';
import 'package:overload_guard/services/api_service.dart';
import 'package:overload_guard/services/db_service.dart';
import 'package:overload_guard/widgets/buttons.dart';
import 'package:overload_guard/widgets/dialogs.dart';

class SignInPage extends StatefulWidget {
  @override
  State<SignInPage> createState() => _SignInPageState();
}

class _SignInPageState extends State<SignInPage> {
  TextEditingController accountController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  bool _rememberMe = false;

  @override
  void initState() {
    initData();
    super.initState();
  }

  initData() async {
    // 处理记住密码
    var rememberMe = await DBService.getData<bool?>(DBKey.userSignInRememberMe);
    print('rememberMe:$rememberMe');
    var account = await DBService.getData<String?>(DBKey.userSignInAccount);
    var password = await DBService.getData<String?>(DBKey.userSignInPassword);

    if (rememberMe == true && account != null && password != null) {
      _rememberMe = true;
      accountController.text = account;
      passwordController.text = password;
    }

    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.only(left: 30, right: 30),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Padding(padding: EdgeInsets.only(top: 40)),
              Image(image: AssetImage("assets/truck.webp")),
              Text(
                '超偏载检测系统',
                style: Theme.of(context).textTheme.titleLarge,
              ),
              Padding(padding: EdgeInsets.only(top: 30)),
              TextField(
                controller: accountController,
                decoration: InputDecoration(
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey)),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: AppTheme.primaryColor)),
                    hintText: "输入账号",
                    labelText: "账号"),
              ),
              Padding(padding: EdgeInsets.only(top: 10)),
              TextField(
                controller: passwordController,
                decoration: InputDecoration(
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey)),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: AppTheme.primaryColor)),
                    hintText: "输入密码",
                    labelText: "密码"),
                obscureText: true,
                enableSuggestions: false,
                autocorrect: false,
              ),
              Padding(padding: EdgeInsets.only(top: 10)),
              GestureDetector(
                onTap: () {
                  setState(() {
                    _rememberMe = !_rememberMe;
                  });
                },
                child: Row(
                  children: [
                    Checkbox(
                        value: _rememberMe,
                        onChanged: (v) {
                          setState(() {
                            _rememberMe = v == true;
                          });
                        }),
                    Text("记住用户名和密码")
                  ],
                ),
              ),
              mainSubmitButton("登陆", _signIn, context, AppTheme.primaryColor),
              Padding(padding: EdgeInsets.only(top: 10)),
              mainSubmitButton("退出", () {
                Get.back();
              }, context, Colors.grey),
            ],
          ),
        ),
      ),
    );
  }

  _signIn() async {
    // 调用接口
    var loginResult = await APIService.loginToken(password: passwordController.text, phone: accountController.text);

    var success = loginResult != null;

    if (success) {
      await DBService.saveData(DBKey.userSignInStatus, true);

      // 存储信息
      await DBService.saveData(DBKey.userId, loginResult["userId"]);
      await DBService.saveData(DBKey.userToken, loginResult["token"]);
      await DBService.saveData(DBKey.userPhone, accountController.text);

      Dialogs.showSuccess(title: "成功", body: "登录成功");

      // 记住密码
      if (_rememberMe) {
        DBService.saveData(DBKey.userSignInRememberMe, true);
        DBService.saveData(DBKey.userSignInAccount, accountController.text);
        DBService.saveData(DBKey.userSignInPassword, passwordController.text);
      } else {
        DBService.saveData(DBKey.userSignInRememberMe, false);
        DBService.saveData(DBKey.userSignInAccount, null);
        DBService.saveData(DBKey.userSignInPassword, null);
      }

      // 跳转首页
      Get.offAll(MyHomePage());
    }
  }
}
